package config

import (
	"github.com/pkg/errors"
	"gopkg.in/yaml.v2"
	"io/ioutil"
)

const (
	LOGRUS string = "logrus"
	ZAP    string = "zap"
)

type AppConfig struct {
	MasterMySqlConfig DatabaseConfig `yaml:"master-mysql-config"`
	SlaveMySqlConfig  DatabaseConfig `yaml:"slave-mysql-config"`
	UserGrpcConfig    DatabaseConfig `yaml:"user-grpc-config"`
	ZapConfig         LogConfig      `yaml:"zap-config"`
	LogrusConfig      LogConfig      `yaml:"logrus-config"`
	Log               LogConfig      `yaml:"log-config"`
	UserConfig        UserConfig     `yaml:"user-config"`
}

type DatabaseConfig struct {
	Code       string `yaml:"code"`
	DriverName string `yaml:"driver-name"`
	UrlAddress string `yaml:"url-address"`
	DbName     string `yaml:"db-name"`
}

type LogConfig struct {
	Code         string `yaml:"code"`
	Level        string `yaml:"level"`
	EnableCaller bool   `yaml:"enable-caller"`
	FileName     string `yaml:"file-name"`
}

type UserConfig struct {
	Database Database `yaml:"database"`
	Service  Service  `yaml:"service"`
}

type Database struct {
	Master DatabaseConfig `yaml:"master"`
	Slave  DatabaseConfig `yaml:"slave"`
}

type Service struct {
	User DatabaseConfig `yaml:"user"`
}

func ReadConfig(filename string) (*AppConfig, error) {
	var appConfig AppConfig
	file, err := ioutil.ReadFile(filename)
	if err != nil {
		return nil, errors.Wrap(err, "read config error.")
	}
	err = yaml.Unmarshal(file, &appConfig)
	if err != nil {
		return nil, errors.Wrap(err, "parse config error.")
	}
	err = validateConfig(appConfig)
	if err != nil {
		return nil, errors.Wrap(err, "validate config error.")
	}
	return &appConfig, nil
}
